package com.example.study;

import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Objects;

@Slf4j
public class SpringUtils {

    private static ApplicationContext context = null;


    public static void setApplicationContext(ApplicationContext context) {
        SpringUtils.context = context;
    }

    public static ApplicationContext getApplicationContext() {
        return context;
    }


    /**
     * 通过 name 获取bean
     *
     * @param name name
     * @return bean
     */
    public static Object getBean(@NotEmpty String name) {
        validate();
        return getApplicationContext().getBean(name);
    }


    /**
     * 通过 class 获取bean
     *      例： IUserService userService = SpringUtils.getBean(IUserService.class)
     *
     * @param clazz clazz
     * @param <T> 泛型
     * @return bean
     */
    public static <T> T getBean(@NotNull Class<T> clazz) {
        validate();
        return context.getBean(clazz);
    }


    /**
     * 根据 name 和 class 获取bean
     *
     * @param name name
     * @param clazz clazz
     * @param <T> 泛型
     * @return bean
     */
    public static <T> T getBean(@NotEmpty String name, @NonNull Class<T> clazz) {
        validate();
        return getApplicationContext().getBean(name, clazz);
    }


    /**
     * 校验 applicationContext 是否为空
     */
    private static void validate() {
        if (Objects.isNull(context)) {
//            throw new CosyException(CodeMsg.APPLICATION_CONTEXT_IS_EMPTY);
        }
    }
}